import { useState, useEffect } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { useParams, useNavigate } from 'react-router-dom'

export default function CircleDetailPage() {
  const { circleId } = useParams()
  const navigate = useNavigate()
  const [activeTab, setActiveTab] = useState('map') // 'map', 'chat', 'members'
  const [circle, setCircle] = useState(null)
  const [members, setMembers] = useState([])
  const [messages, setMessages] = useState([])
  const [newMessage, setNewMessage] = useState('')

  useEffect(() => {
    loadCircleData()
  }, [circleId])

  const loadCircleData = async () => {
    // 模拟数据
    setCircle({
      id: circleId,
      name: '黄山徒步团',
      description: '一起征服黄山的美景',
      member_count: 8
    })

    setMembers([
      { id: 1, nickname: '户外探险者', phone: '138****8000', latitude: 30.1234, longitude: 118.1234, last_active: '刚刚' },
      { id: 2, nickname: '山峰征服者', phone: '139****9000', latitude: 30.1235, longitude: 118.1235, last_active: '5分钟前' },
      { id: 3, nickname: '自然爱好者', phone: '137****7000', latitude: 30.1236, longitude: 118.1236, last_active: '10分钟前' }
    ])

    setMessages([
      { id: 1, user: '户外探险者', content: '大家好，我已经到达集合点了！', time: '10:30', type: 'text' },
      { id: 2, user: '山峰征服者', content: '我也快到了，还有5分钟', time: '10:32', type: 'text' },
      { id: 3, user: '自然爱好者', content: '天气真不错，适合徒步', time: '10:35', type: 'text' }
    ])
  }

  const sendMessage = () => {
    if (!newMessage.trim()) return

    const message = {
      id: Date.now(),
      user: '户外探险者',
      content: newMessage,
      time: new Date().toLocaleTimeString('zh-CN', { hour: '2-digit', minute: '2-digit' }),
      type: 'text'
    }

    setMessages([...messages, message])
    setNewMessage('')
  }

  const renderMapView = () => (
    <div className="h-full bg-gray-100 rounded-lg p-4">
      <div className="text-center mb-4">
        <h3 className="font-semibold text-gray-800">实时位置</h3>
        <p className="text-sm text-gray-600">圈子成员位置分布</p>
      </div>
      
      {/* 模拟地图 */}
      <div className="bg-green-50 rounded-lg h-64 relative border-2 border-green-200">
        <div className="absolute inset-0 flex items-center justify-center">
          <div className="text-center">
            <div className="text-4xl mb-2">🗺️</div>
            <p className="text-green-700 font-medium">地图视图</p>
            <p className="text-sm text-green-600">显示成员实时位置</p>
          </div>
        </div>
        
        {/* 模拟用户位置点 */}
        {members.map((member, index) => (
          <div 
            key={member.id}
            className="absolute w-8 h-8 bg-walker-orange rounded-full flex items-center justify-center text-white text-xs font-bold shadow-lg"
            style={{
              left: `${20 + index * 25}%`,
              top: `${30 + index * 15}%`
            }}
          >
            {member.nickname.charAt(0)}
          </div>
        ))}
      </div>

      <div className="mt-4 space-y-2">
        <h4 className="font-medium text-gray-800">在线成员 ({members.length})</h4>
        {members.map(member => (
          <div key={member.id} className="flex justify-between items-center p-2 bg-white rounded border">
            <div>
              <span className="font-medium">{member.nickname}</span>
              <span className="text-sm text-gray-500 ml-2">{member.last_active}</span>
            </div>
            <div className="w-3 h-3 bg-green-500 rounded-full"></div>
          </div>
        ))}
      </div>
    </div>
  )

  const renderChatView = () => (
    <div className="h-full flex flex-col">
      {/* 消息列表 */}
      <div className="flex-1 overflow-y-auto space-y-3 mb-4">
        {messages.map(message => (
          <div key={message.id} className="bg-white rounded-lg p-3 shadow-sm">
            <div className="flex justify-between items-start mb-1">
              <span className="font-medium text-sm text-gray-800">{message.user}</span>
              <span className="text-xs text-gray-500">{message.time}</span>
            </div>
            <p className="text-gray-700">{message.content}</p>
          </div>
        ))}
      </div>

      {/* 消息输入 */}
      <div className="flex space-x-2">
        <Input
          placeholder="输入消息..."
          value={newMessage}
          onChange={(e) => setNewMessage(e.target.value)}
          onKeyPress={(e) => e.key === 'Enter' && sendMessage()}
          className="flex-1"
        />
        <Button 
          onClick={sendMessage}
          className="bg-walker-orange hover:bg-walker-orange/90"
          disabled={!newMessage.trim()}
        >
          发送
        </Button>
      </div>
    </div>
  )

  const renderMembersView = () => (
    <div className="space-y-3">
      <div className="text-center mb-4">
        <h3 className="font-semibold text-gray-800">圈子成员</h3>
        <p className="text-sm text-gray-600">共 {members.length} 人</p>
      </div>

      {members.map(member => (
        <div key={member.id} className="bg-white rounded-lg p-4 shadow-sm border">
          <div className="flex justify-between items-center">
            <div>
              <h4 className="font-medium text-gray-800">{member.nickname}</h4>
              <p className="text-sm text-gray-500">{member.phone}</p>
              <p className="text-xs text-gray-400">最后活跃: {member.last_active}</p>
            </div>
            <div className="text-right">
              <div className="w-3 h-3 bg-green-500 rounded-full mb-1"></div>
              <span className="text-xs text-gray-500">在线</span>
            </div>
          </div>
        </div>
      ))}
    </div>
  )

  if (!circle) {
    return (
      <div className="min-h-screen bg-gray-50 flex items-center justify-center">
        <div className="text-center">
          <div className="text-2xl mb-2">⏳</div>
          <p className="text-gray-600">加载中...</p>
        </div>
      </div>
    )
  }

  return (
    <div className="min-h-screen bg-gray-50 flex flex-col">
      {/* 头部 */}
      <div className="bg-white shadow-sm border-b">
        <div className="max-w-md mx-auto px-4 py-4">
          <div className="flex items-center space-x-3">
            <Button 
              variant="outline" 
              size="sm"
              onClick={() => navigate('/circles')}
            >
              ← 返回
            </Button>
            <div>
              <h1 className="font-bold text-gray-800">{circle.name}</h1>
              <p className="text-sm text-gray-600">{circle.description}</p>
            </div>
          </div>
        </div>
      </div>

      {/* 标签页导航 */}
      <div className="bg-white border-b">
        <div className="max-w-md mx-auto px-4">
          <div className="flex">
            {[
              { key: 'map', label: '地图', icon: '🗺️' },
              { key: 'chat', label: '聊天', icon: '💬' },
              { key: 'members', label: '成员', icon: '👥' }
            ].map(tab => (
              <button
                key={tab.key}
                onClick={() => setActiveTab(tab.key)}
                className={`flex-1 py-3 text-center border-b-2 transition-colors ${
                  activeTab === tab.key
                    ? 'border-walker-orange text-walker-orange'
                    : 'border-transparent text-gray-600 hover:text-gray-800'
                }`}
              >
                <span className="mr-1">{tab.icon}</span>
                {tab.label}
              </button>
            ))}
          </div>
        </div>
      </div>

      {/* 主要内容 */}
      <div className="flex-1 max-w-md mx-auto w-full p-4">
        {activeTab === 'map' && renderMapView()}
        {activeTab === 'chat' && renderChatView()}
        {activeTab === 'members' && renderMembersView()}
      </div>
    </div>
  )
}

